package com.server.questionbank.snframe.service.CourseService.Impl;

import com.server.questionbank.snframe.domain.Course.CourseComment;
import com.server.questionbank.snframe.domain.Course.Result.RCourseComment;
import com.server.questionbank.snframe.mapper.Course.CourseCommentMapper;
import com.server.questionbank.snframe.service.CourseService.CourseCommentService;
import com.server.questionbank.snframe.service.UsersService.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CourseCommentServiceImpl implements CourseCommentService {
    @Autowired
    private CourseCommentMapper courseCommentMapper;
    @Autowired
    private UsersService usersService;

    // 查询单个评论
    @Override
    public RCourseComment selectCourseCommentById(Long commentId) {
        return courseCommentMapper.selectCourseCommentById(commentId).toRCourseComment(usersService);
    }

    // 查询课程下的所有评论
    @Override
    public List<RCourseComment> selectCourseCommentByCourseId(Long courseId) {
        List<RCourseComment> courseComments = courseCommentMapper.selectCourseCommentByCourseId(courseId)
                .stream().map(courseComment -> courseComment.toRCourseComment(usersService)).collect(Collectors.toList());
        return getCourseComments(courseComments);
    }

    // 递归查询
    private List<RCourseComment> getCourseComments(List<RCourseComment> courseComments) {
        courseComments.forEach(courseComment -> {
            List<RCourseComment> children = courseCommentMapper.selectCourseCommentByParentId(courseComment.getCommentId())
                    .stream().map(courseComment1 -> courseComment1.toRCourseComment(usersService)).collect(Collectors.toList());
            if (children.size() > 0) courseComment.setChildren(getCourseComments(children));
        });
        return courseComments;
    }

    // 插入课程评论
    @Override
    public Boolean insertCourseComment(CourseComment courseComment) {
        if (courseComment == null) return false;
        if (courseComment.getParentId() == null) courseComment.setParentId(0L);
        return courseCommentMapper.insertCourseComment(courseComment) > 0;
    }

    // 删除课程评论
    @Override
    public Boolean deleteCourseComment(Long commentId) {
        if (commentId == null) return true;
        List<Long> commentIds = courseCommentMapper.selectCourseCommentByParentId(commentId)
                .stream().map(CourseComment::getCommentId).collect(Collectors.toList());
        for (Long commentId1 : commentIds) if(deleteCourseComment(commentId1) == false) return false;
        return courseCommentMapper.deleteCourseComment(commentId) > 0;
    }
}
